﻿using HY.Common;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using WpfApp.Models;

namespace WpfApp.Views
{
    /// <summary>
    /// DataGridView.xaml 的交互逻辑
    /// </summary>
    public partial class DataGridView : Window
    {
        public DataGridView()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            List<SongModel> list = new List<SongModel>();
            list.AddRange(new SongModel[] {
                new SongModel() { Icon="/WpfApp;component/Resources/Images/music.png", Name = "七里香", AlbumTitle = "叶惠美", Lenght = 800, Singer = "周杰伦", Url = "七里香.mp3" },
                new SongModel() { Icon="/WpfApp;component/Resources/Images/music.png", Name = "外婆", AlbumTitle = "叶惠美", Lenght = 800, Singer = "周杰伦", Url = "外婆.mp3" },
                new SongModel() { Icon="/WpfApp;component/Resources/Images/music.png", Name = "将军", AlbumTitle = "叶惠美", Lenght = 800, Singer = "周杰伦", Url = "将军.mp3" },
                new SongModel() { Icon="/WpfApp;component/Resources/Images/music.png", Name = "搁浅", AlbumTitle = "叶惠美", Lenght = 800, Singer = "周杰伦", Url = "搁浅.mp3" },
            });
            //自动生成列需设为false，否则会叠加下面的设置列
            DgAuto.AutoGenerateColumns = false;
            //根据属性DisplayName动态绑定列
            foreach (var item in ModelHelper.ColumnMapping<SongModel>())
            {
                if (item.Key.ToLower() != "icon")
                    //可根据相关判断，设置Binding使用的转换器
                    DgAuto.Columns.Add(new DataGridTextColumn() { Header = item.Value, Binding = new Binding(item.Key) });
                else
                {
                    //创建DataGridTemplateColumn        
                    var column = new DataGridTemplateColumn();
                    column.CanUserResize = false;
                    column.CanUserReorder = false;
                    column.Header = item.Value;
                    //创建FrameworkElementFactory
                    var img = new FrameworkElementFactory(typeof(Image));
                    //创建绑定
                    Binding binding = new Binding(item.Key);
                    //设置转换器,用于转换流图片
                    //binding.Converter = new ImageConverter();
                    img.SetBinding(Image.SourceProperty, binding);
                    img.SetValue(Image.HeightProperty, 30.00);
                    //创建数据模板
                    var template = new DataTemplate
                    {
                        VisualTree = img
                    };
                    column.CellTemplate = template;

                    DgAuto.Columns.Add(column);
                }
            }
            DgAuto.ItemsSource = list;
        }
    }
}
